#include "mqtt.hpp"

WiFiClient _mqttWifiClient;

Mqtt::Mqtt(HADevice &device)
{
    mqttClient = new HAMqtt(_mqttWifiClient, device);
}

Mqtt::~Mqtt()
{
    delete mqttClient;
}

boolean Mqtt::connect()
{
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print("wait for wifi.");
    }
    Serial.printf("mqtt server:%s, port:%d, user:%s, pass:%s\n", mServerHost.c_str(), mServerPort, mUserName.c_str(), mUserPass.c_str());
    if (mUserName.length() > 0 && mqttClient->begin(mServerHost.c_str(), mServerPort, mUserName.c_str(), mUserPass.c_str()))
    {
        // 订阅消息
        Serial.println("mqtt connected success");
    }
    else if (mqttClient->begin(mServerHost.c_str(), mServerPort, NULL, NULL))
    {
        // 订阅消息
        Serial.println("mqtt connected success");
    } else {
        Serial.println("mqtt connected err");
    }
    return mqttClient->isConnected();
}

void Mqtt::loop()
{
    return mqttClient->loop();
}

boolean Mqtt::connected()
{
    return mqttClient->isConnected();
}

void Mqtt::setServer(char *server, uint16_t port)
{
    mServerHost = server;
    mServerPort = port;
}

void Mqtt::setUser(char *name, char *pass)
{
    mUserName = name;
    mUserPass = pass;
}
